import { NestFactory } from '@nestjs/core'
import { VersioningType } from '@nestjs/common/enums'
import { AppModule } from './app.module'
import * as session from 'express-session'
import { Request, Response, NextFunction } from 'express'
import * as cors from 'cors'
import { NestExpressApplication } from '@nestjs/platform-express/interfaces'
import { join } from 'path'
import { MyResponse } from './common/response'
import { HttpFilter } from './common/filters'
import { ValidationPipe } from '@nestjs/common'
import { RoleGuard } from './guard/role/role.guard'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
const blackList = ['/ikun']

function MiddlewareG(req: Request, res: Response, next: NextFunction) {
  //全局中间件
  console.log(req.originalUrl)
  if (blackList.includes(req.originalUrl)) {
    res.send('小黑子，露出鸡脚了吧')
  }
  next()
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule)

  //swagger接口文档文档
  const swaggerOptions = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('Demo的接口文档')
    .setDescription('第一次尝试使用swagger')
    .setVersion('1.0.0')
    .build()
  const swaggerDocument = SwaggerModule.createDocument(app, swaggerOptions)
  SwaggerModule.setup('/api-docs', app, swaggerDocument)

  app.useGlobalPipes(new ValidationPipe())
  app.useGlobalInterceptors(new MyResponse())
  app.useGlobalFilters(new HttpFilter())
  // app.useGlobalGuards(new RoleGuard)
  app.useStaticAssets(join(__dirname, 'images'), {
    prefix: '/img',
  })
  app.enableVersioning({
    type: VersioningType.URI,
  })
  app.use(
    session({
      secret: 'JiaYan', //加盐
      name: 'bl.session', //生成的客户端cookie名字  默认为 connect.sid
      rolling: true, //在每次请求时强制设置 cookie 这将重置 cookie 过期时间(默认:false)
      cookie: { maxAge: 99999 }, //设置返回到前端 key 的属性，默认值为{ path: ‘/’, httpOnly: true, secure: false, maxAge: null }。
    })
  )
  app.use(cors())
  app.use(MiddlewareG) //在此处挂载到app上
  await app.listen(3000)
}
bootstrap()
